﻿/*************************************************************************
 * Created by OhZee Creative, LLC
 * 2013
 * This code is licensed under Microsoft Public License (Ms-PL)
 * http://opensource.org/licenses/ms-pl
 * http://ozframework.codeplex.com/
 *************************************************************************/

namespace OhZeeCreative.Windows8
{
    using OhZeeCreative.Helpers;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Data;

    public sealed class BoundControl : ContentControl
	{
		public static readonly DependencyProperty ModeProperty = DependencyProperty.Register("Mode", typeof(BindingMode), typeof(BoundControl), new PropertyMetadata(BindingMode.OneWay));
		public static readonly DependencyProperty BoundToProperty = DependencyProperty.Register("BoundTo", typeof(string), typeof(BoundControl), new PropertyMetadata(null));

		public BindingMode Mode
		{
			get { return (BindingMode)GetValue(ModeProperty); }
			set { SetValue(ModeProperty, value); }
		}

		public string BoundTo
		{
			get { return (string)GetValue(BoundToProperty); }
			set { SetValue(BoundToProperty, value); }
		}
		
		
		public BoundControl()
		{
			//this.DefaultStyleKey = typeof(BoundControl);
			this.DefaultStyleKey = typeof(ContentControl);
		}

		public DependencyObject TargetObject
		{
			get { return this.Content as DependencyObject; }
		}

		public DependencyProperty TargetProperty
		{
			get
			{
				DependencyObject dob = this.TargetObject;
				if (dob != null)
				{
					if (string.IsNullOrEmpty(this.BoundTo))
					{
						return GetDefaultTargetProperty(dob);
					}

					return ReflectionHelper.GetPropertyAsDependencyProperty(dob, this.BoundTo);
				}
				return null;
			}
		}

		public static DependencyProperty GetDefaultTargetProperty(DependencyObject targetObject)
		{
			if (typeof(TextBlock).Equals(targetObject.GetType()))
			{
				return TextBlock.TextProperty;
			}
			else if (typeof(CheckBox).Equals(targetObject.GetType()))
			{
				return CheckBox.IsEnabledProperty;
			}
			else if (typeof(Slider).Equals(targetObject.GetType()))
			{
				return Slider.ValueProperty;
			}

			return null;
		}
	}
}
